<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { NModal, NCard, NSpin } from 'naive-ui';
import * as echarts from 'echarts';

const visible = ref(false);
const loading = ref(false);
const instanceIds = ref<number[]>([]);
const chartRef = ref<HTMLDivElement>();
let chartInstance: echarts.ECharts | null = null;

const open = (ids: number[]) => {
  instanceIds.value = ids;
  visible.value = true;
  setTimeout(() => {
    initChart();
  }, 100);
};

const initChart = () => {
  if (!chartRef.value) return;

  chartInstance = echarts.init(chartRef.value);

  const option = {
    title: {
      text: '实例性能指标',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['执行时长', '重试次数'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: instanceIds.value.map(id => `实例${id}`)
    },
    yAxis: [
      {
        type: 'value',
        name: '时长(秒)',
        position: 'left'
      },
      {
        type: 'value',
        name: '次数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '执行时长',
        type: 'bar',
        data: instanceIds.value.map(() => Math.floor(Math.random() * 300))
      },
      {
        name: '重试次数',
        type: 'line',
        yAxisIndex: 1,
        data: instanceIds.value.map(() => Math.floor(Math.random() * 5))
      }
    ]
  };

  chartInstance.setOption(option);
};

const handleClose = () => {
  visible.value = false;
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
};

defineExpose({
  open
});
</script>

<template>
  <NModal v-model:show="visible" preset="card" title="性能指标" class="w-1000px" @after-leave="handleClose">
    <NSpin :show="loading">
      <div ref="chartRef" class="h-500px"></div>
    </NSpin>
  </NModal>
</template>

<style scoped></style>
